package initialize

import (
	"awesomeProject/global"
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"os"
)

var mgoCli *mongo.Client

func initEngine() {
	var err error
	mongodbCfg := global.Config.MongodbConf
	clientOptions := options.Client().
		ApplyURI(fmt.Sprintf("mongodb://%s:%d", mongodbCfg.Host, mongodbCfg.Port)).
		SetAuth(options.Credential{
			// 用户名
			Username: mongodbCfg.Username,
			// 密码
			Password: mongodbCfg.Password,
		})

	// 连接到MongoDB
	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		fmt.Println("mongodb启动异常，err:", err)
		os.Exit(0)
	}
	// 检查连接
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		fmt.Println("mongodb启动异常，err:", err)
		os.Exit(0)
	}
}
func MongoDBInit() *mongo.Database {
	if mgoCli == nil {
		initEngine()
	}
	return mgoCli.Database(global.Config.MongodbConf.DB)
}
